#include "sqliteDataBase.h"

stdsqliteDataBase::stdsqliteDataBase() :m_db(nullptr)
{}

stdsqliteDataBase::~stdsqliteDataBase() 
{}

bool stdsqliteDataBase::connectDB(const std::string &dbFileName) {


    int ret=sqlite3_open(dbFileName.c_str(),&m_db);
    if(ret!=SQLITE_OK)
    {
        cout << "sqlite3 open error" << sqlite3_errmsg(m_db) << endl;
        return false;
    }
    return true;
}

bool stdsqliteDataBase::execute(const std::string &sql)
{
    //执行sql语句
    int ret=sqlite3_exec(m_db,sql.c_str(),NULL,NULL,NULL);
    if(ret!=SQLITE_OK)
    {
        cout << "sqlite3 open error" << sqlite3_errmsg(m_db) << endl;
        return false;
    }
    return true;
}

vector<vector<string>> stdsqliteDataBase::query(const std::string &sql)
{
    vector<vector<string>> Datas;
    //查看数据
    char **buffer=NULL;
    int row = 0;
    int column = 0;
    int ret = sqlite3_get_table(m_db, sql.c_str(), &buffer,&row ,&column , NULL);
    if(ret!=SQLITE_OK)
    {
        cout << "sqlite3 get tabel error" << sqlite3_errmsg(m_db) << endl;
        return Datas;
    }
    for (int i = 1; i <= row; i++)
    {
        vector<string> rowData;
        for (int j = 0; j < column; j++)
        {
        //cout << left << setw(16) << buffer[i * column + j];
        rowData.push_back(buffer[i * column + j]);
        }
        Datas.push_back(rowData);
    }
    return Datas;
}

void stdsqliteDataBase::closeDB()
{
    sqlite3_close(m_db);
}
